import {createStore, applyMiddleware, StoreEnhancer, StoreEnhancerStoreCreator, Store, MiddlewareAPI,Dispatch,AnyAction} from '../redux';
import rootReducer, { CombinedState } from './reducers';
import *  as TYPES from '../store/action-types';

const logger = function (api: any) {//api
  return function (next: any) {//下一个中间件
    return function (action: any) {//派发的动作
      console.log('变更前的老状态2', api.getState());//store.dispatch
      next(action);//调用下一个中间件 store.dispatch
      console.log('变更后的新状态2', api.getState());
    }
  }
};

const thunk = function (api: MiddlewareAPI) {//api
  return function (next: Dispatch<AnyAction>) {//下一个中间件  store.dispatch
    return function (action: any) {//派发的动作

      //如果action是一个函数,则可以让函数执行
      if (typeof action === 'function') {
        return action(api.dispatch, api.getState);
      }
      //如果说不是一个函数,则可以直接调用下一步
      return next(action);
    }
  }
};
function isPromise(obj: any) {
  return !!obj && (typeof obj === 'object') && typeof obj.then === 'function'
}
const promise = function (api: MiddlewareAPI) {//api
  return function (next: Dispatch<AnyAction>) {//下一个中间件
    //以后再调用store.dispatch调用就是这个函数
    return function (action: any) {//派发的动作
      return isPromise(action.payload) ? action.payload.then(
        (result: any) => api.dispatch({ ...action, payload: result }),
        (error: any) => {
          api.dispatch({ ...action, payload: error, error: true });
          return Promise.reject(error);
        }
      ) : next(action)
    }
  }
}

//如果有中间件的话，创建仓库要经过三步
const storeEnhancer: StoreEnhancer = applyMiddleware<{}, CombinedState>(thunk, logger);//返回一个Store的增强器 洋葱模型 右边的靠里(store.dispatch) 左边的中间件在外
const storeEnhancerStoreCreator: StoreEnhancerStoreCreator = storeEnhancer(createStore);//返回一个增强后的createStore方法
const store: Store<CombinedState> = storeEnhancerStoreCreator<CombinedState>(rootReducer);//返回仓库
//const store = createStore(rootReducer);
export default store;
